//
//  ALPullDownRefreshControl.swift
//  ALSinaWeiBoSwift
//
//  Created by 柴瑞军 on 16/4/16.
//  Copyright © 2016年 myCompany. All rights reserved.
//

import UIKit
//刷新控件的高度
private let ALPullDownRefreshControlHeight: CGFloat = 60

//刷新控件的三种状态
enum ALPullDownRefreshControlStatus:Int {
    case Normal //箭头朝下 下拉刷新
    case PullToRefresh //箭头朝上 释放刷新
    case Refreshing //正在刷新
}
//下拉刷新控件
class ALPullDownRefreshControl: UIView {
    
    //1.定义刷新闭包
    var pullDownRefreshHandler : (()->())?
    
    
    //MARK: - 属性
    private var superScrollView: UIScrollView?
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override init(frame: CGRect) {
        
        let newFrame = CGRect(x: 0, y: -ALPullDownRefreshControlHeight, width: UIScreen.mainScreen().bounds.width, height: ALPullDownRefreshControlHeight)
        
        
        super.init(frame: newFrame)
        
        //添加控件
        
        preparaUI()
    }
    private func preparaUI(){
//        backgroundColor = UIColor.randomColor()
        addSubview(arrowView)
        addSubview(loadImageView)
        addSubview(messageLabel)
        
//        默认先隐藏loadImage
        loadImageView.hidden = true
        
//        设置约束
        loadImageView.snp_makeConstraints { (make) in
            make.centerX.equalTo(self).offset(-30)
            make.centerY.equalTo(self)
        }
        
        arrowView.snp_makeConstraints { (make) in
            make.centerX.equalTo(loadImageView)
            make.centerY.equalTo(loadImageView)
        }
        
        messageLabel.snp_makeConstraints { (make) in
            make.leading.equalTo(loadImageView.snp_trailing).offset(10)
            make.centerY.equalTo(loadImageView)
        }
    }
    //当前刷新的状态;  默认是普通状态
    private var currentStatus : ALPullDownRefreshControlStatus = ALPullDownRefreshControlStatus.Normal{
        //当状态切换了,根据不同的状态设置不同内容
        didSet{
            switch currentStatus {
            case .Normal:
                //影藏加载数据的图片
                loadImageView.hidden = true
                //显示箭头
                arrowView.hidden = false
                
                //箭头回到初始的位置  文字显示 下啦刷新
                messageLabel.text =  "下拉刷新"
                UIView.animateWithDuration(alDefaultTimeInterval, animations: { 
                    self.arrowView.transform = CGAffineTransformIdentity
                })
            case .PullToRefresh:
                //箭头旋转方向,文字显示 释放刷新
                
                UIView.animateWithDuration(alDefaultTimeInterval, animations: { 
                    self.arrowView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                messageLabel.text = "释放刷新"
            case .Refreshing:
                //显示文字内容 正在刷新
                loadImageView.hidden = false
                arrowView.hidden = true
                
                messageLabel.text = "正在刷新..."
                
                //添加动画
                let animation = CABasicAnimation(keyPath: "transform.rotation")
                animation.toValue = M_PI_2
                animation.repeatCount = MAXFLOAT
                animation.duration = 0.5
                animation.removedOnCompletion = false
                // 给动画加forKey: 如果下次再添加一个和之前已经存在的动画,先停止之前的动画,在使用这次的动画, 防止动画重复添加
                loadImageView.layer.addAnimation(animation, forKey: "animation")
                // 让tableView往下走HMPullDownRefreshControlHeight, 刷新控件就不会被导航栏挡住
                UIView.animateWithDuration(alDefaultTimeInterval, animations: { 
                    self.superScrollView?.contentInset.top += ALPullDownRefreshControlHeight
                })
                
                //调用闭包:告诉别人开始刷新了
                pullDownRefreshHandler?()
            }
            
        }
    }
    
    //刷新结束调用的方法
    func endRefreshing(){
    
        //Refreshing切换到normal
        currentStatus = .Normal
        //只有从refresh切换到naomal才需要去contentInset.top - HMPullDownRefreshControlHeight
        //让tableview往上走HMPullDownRefreshControlHeight 刷新控件就看不到了
        UIView.animateWithDuration(alDefaultTimeInterval) { 
            self.superScrollView?.contentInset.top -= ALPullDownRefreshControlHeight
        }
    }
    
    /// 开始刷新
    func startRefreshing() {
        // 将状态切换到Refreshing
        currentStatus = .Refreshing
    }

    
//    当控件添加到父控件后会调用这个方法,在这个时候可以拿到父控件
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        
        //判断父控件是UIScrollView或其子类
        if let scrollView = newSuperview as? UIScrollView{
        //用属性记录
           superScrollView = scrollView
            
            
            //使用KVO来监听scrollview的滚动
            // 使用KVO来监听scrollView的滚动
            // 要监听谁的属性,就用谁来调用
            // observer: 谁来处理监听事件
            // forKeyPath: 想监听的属性
            // options: 监听选项, 新值,老得值
            // context: 上下文
            
            superScrollView?.addObserver(self, forKeyPath: "contentOffset", options: [], context: nil)
        }
    }
    //KVO 需要移除
    deinit{
        removeObserver(self, forKeyPath: "contentOffset")
    }
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
//        ALPrint("superScrollView?.contentOffset.y = \(superScrollView?.contentOffset.y )")
        //用户手指在拖动的时候在PullToRefresh和Normal之间切换
        if superScrollView!.dragging {
            if currentStatus == .PullToRefresh && superScrollView?.contentOffset.y > (superScrollView!.contentInset.top + ALPullDownRefreshControlHeight){
                ALPrint("切换到Normal")
                currentStatus = .Normal
            }else if currentStatus == .Normal && superScrollView?.contentOffset.y<(superScrollView!.contentInset.top + ALPullDownRefreshControlHeight){
                
                ALPrint("切换到了刷新状态")
                currentStatus = .PullToRefresh
            }
        }else if currentStatus == .PullToRefresh{
        
            currentStatus = .Refreshing
            
        }
    }
    //MARK: - 懒加载控件
    //箭头控件
    private lazy var arrowView : UIImageView = UIImageView(imageNamed: "tableview_pull_refresh")
    //加载控件
    private lazy var loadImageView: UIImageView = UIImageView(imageNamed: "tableview_loading")
    //加载信息的label
    private lazy var messageLabel: UILabel = {
        let label = UILabel(fontSize: 14, textColor: UIColor.darkGrayColor())
        
        label.text = "下拉刷新"
        
        return label
    }()
}
